import tensorflow as tf
import os
import matplotlib.pyplot as plt


def tanh(x):
    return (tf.exp(x) - tf.exp(-x)) / (tf.exp(x) + tf.exp(-x))


if __name__ == '__main__':
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
    # 准备 x 输入向量
    x = tf.linspace(-10, 10, 100)

    # y = tanh(x)
    # grad = 1 - tf.pow(tanh(x), 2)
    y = tf.nn.tanh(x)
    grad = 1 - tf.pow(tf.nn.tanh(x), 2)
    print(y)

    plt.plot(x, y, color='r', label="tanh")
    plt.plot(x, grad, color='y', label='tanh gradient')
    # 设置图例
    plt.legend(loc=2)
    plt.title("tanh(x) and tanh gradient")
    plt.grid()
    plt.xlabel(xlabel='x')
    plt.ylabel(ylabel='y')
    plt.xlim(-10, 10)
    # plt.ylim(-1, 1)
    plt.show()
